<?php

/**
 * 开放平台工具类，全功能版
 */
//官方文档API:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=85160b33556181a0c383a7a0ff06117b7f0e727d&lang=zh_CN
namespace App\Models;

use Cache;

class Open extends BaseModel
{
    const COMPONENT_VERIFY_TICKET = 'COMPONENT_VERIFY_TICKET';
    const COMPONENT_ACCESS_TOKEN = 'COMPONENT_ACCESS_TOKEN';
    const PRE_AUTH_CODE = 'PRE_AUTH_CODE';
    private $token = 'qds';
    private $encodingAesKey = '4NAtAmxNU94eokti4u0dTTK35BzISxU988888888888';
    private $appId = 'wx209a5d9af8122275';
    private $appSecret = 'b874cbce160a73341dfabc77a63160a8';
    public $key;
    public static $block_size = 32;
    public static $OK = 0;
    public static $ValidateSignatureError = -40001;
    public static $ParseXmlError = -40002;
    public static $ComputeSignatureError = -40003;
    public static $IllegalAesKey = -40004;
    public static $ValidateAppidError = -40005;
    public static $EncryptAESError = -40006;
    public static $DecryptAESError = -40007;
    public static $IllegalBuffer = -40008;
    public static $EncodeBase64Error = -40009;
    public static $DecodeBase64Error = -40010;
    public static $GenReturnXmlError = -40011;

    public $nodeNames = [
        'ComponentVerifyTicket',
        'AuthorizerAppid',
        'InfoType',
        'AuthorizationCode',
        'PreAuthCode',
        'Content',
        'ToUserName',
        'FromUserName',
        'MsgType',
        'Event'
    ];


    /**
     * 构造函数
     * @param $token string 公众平台上，开发者设置的token
     * @param $encodingAesKey string 公众平台上，开发者设置的EncodingAESKey
     * @param $appId string 公众平台的appId
     */
    public function setConfig($token, $encodingAesKey, $appId, $appSecret)
    {
        $this->token = $token;
        $this->encodingAesKey = $encodingAesKey;
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }


    public function setKey($k)
    {
        $this->key = base64_decode($k . "=");
    }

    public function getMsgData($nodeNames = [])
    {
        if (!$nodeNames) {
            $nodeNames = $this->nodeNames;
        }
        //加(解)密参数
        $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']);
        $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']);
        $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']);
        //接收的微信加密消息
        $encryptMsg = file_get_contents('php://input');
        //解析加密消息中的解密密文
        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        //解密消息
        $msg = '';
        $errCode = $this->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        if ($errCode['code'] == 0) {
            //print("解密后: " . $msg . "\n");
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            return $this->getDataFromXmlByNodeNames($xml, $nodeNames);
        } else {
            return false;
        }
    }

    public function getDataFromXmlByNodeNames($xml, $nodeNames)
    {
        if (!$nodeNames) {
            return false;
        }
        if (!is_array($nodeNames)) {
            $array_e = $xml->getElementsByTagName($nodeNames);
            if ($array_e->item(0)) {
                return $array_e->item(0)->nodeValue;
            }
            return false;
        }
        $data = [];
        foreach ($nodeNames as $v) {
            $array_e = $xml->getElementsByTagName($v);
            if ($array_e->item(0)) {
                $data[$v] = $array_e->item(0)->nodeValue;
            } else {
                $data[$v] = '';
            }
        }
        return $data;
    }

    public function getComponentVerifyTicketFromXml($msgData)
    {
        if (!$msgData) {
            return false;
        }
        if (isset($msgData['ComponentVerifyTicket']) && $msgData['ComponentVerifyTicket']) {
            Cache::put(self::COMPONENT_VERIFY_TICKET, $msgData['ComponentVerifyTicket'], 10);
            echo 'success';
            $this->open->getComponentAccessToken();
            die();
        }
    }

    //获取授权回调URL
    public function getAuthUrl($callBackUrl)
    {
        $preAuthCode = $this->getPreAuthCode();
        if (!$preAuthCode) {
            $this->error = '获取pre_auth_code失败';
            return false;
        }
        $url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' . $this->appId . '&pre_auth_code=' . $preAuthCode . '&redirect_uri=' . $callBackUrl;
        return $url;
    }

    //获取第三方平台component_access_token
    //第三方平台component_access_token是第三方平台的下文中接口的调用凭据，也叫做令牌（component_access_token）。每个令牌是存在有效期（2小时）的，
    //且令牌的调用不是无限制的，请第三方平台做好令牌的管理，在令牌快过期时（比如1小时50分）再进行刷新。
    public function getComponentAccessToken()
    {
        $tokenData = Cache::get(self::COMPONENT_ACCESS_TOKEN);
        $now = time();
        if (!empty($tokenData) && ($tokenData['expires_time'] - $now > 600)) {
            return $tokenData['component_access_token'];
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
        $data = [
            'component_appid' => $this->appId,
            'component_appsecret' => $this->appSecret,
            'component_verify_ticket' => Cache::get(self::COMPONENT_VERIFY_TICKET)
        ];
        $res = $this->curl_post_ssl($url, json_encode($data));
        if ($res['component_access_token']) {
            $tokenData = [
                'component_access_token' => $res['component_access_token'],
                'expires_time' => $now + 7200
            ];
            Cache::put(self::COMPONENT_ACCESS_TOKEN, $tokenData, 120);
            return $res['component_access_token'];
        }
        return false;
    }

    //获取预授权码pre_auth_code
    //该API用于获取预授权码。预授权码用于公众号或小程序授权时的第三方平台方安全验证。
    public function getPreAuthCode()
    {
        $codeData = Cache::get(self::PRE_AUTH_CODE);
        if (!empty($codeData)) {
            return $codeData['pre_auth_code'];
        }
        $component_access_token = $this->getComponentAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' . $component_access_token;
        $data = [
            'component_appid' => $this->appId,
        ];
        $res = $this->curl_post_ssl($url, json_encode($data));
        if ($res['pre_auth_code']) {
            $codeData = [
                'pre_auth_code' => $res['pre_auth_code'],
                'expires_time' => time() + 600
            ];
            Cache::put(self::PRE_AUTH_CODE, $codeData, 10);
            return $res['pre_auth_code'];
        }
        return false;
    }

//使用授权码换取公众号或小程序的接口调用凭据和授权信息
//该API用于使用授权码换取授权公众号或小程序的授权信息，并换取authorizer_access_token和authorizer_refresh_token。
//授权码的获取，需要在用户在第三方平台授权页中完成授权流程后，在回调URI中通过URL参数提供给第三方平台方。
//请注意，由于现在公众号或小程序可以自定义选择部分权限授权给第三方平台，因此第三方平台开发者需要通过该接口来获取公众号或小程序具体授权了哪些权限，
//而不是简单地认为自己声明的权限就是公众号或小程序授权的权限。
//type值为wx和xcx,分别对应调用公众号和小程序的授权
    public function getAuthorizationAcessToken($aid, $type = 'wx')
    {
        $name = $type == 'wx' ? '公众号' : '小程序';
        $wechatSet = new WechatSet();
        $wechat = $wechatSet->_redisGetOneByAid($aid);
        if (!$wechat[$type . '_authorization_code']) {
            $this->error = '该商户' . $name . '暂未授权';
            return false;
        }
        if ($wechat[$type . '_authorizer_access_token']) {
            $this->error = '该商户' . $name . '已获取authorizer_access_token，请调用更新方法';
            return false;
        }
        $component_access_token = $this->getComponentAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' . $component_access_token;
        $data = [
            'component_appid' => $this->appId,
            'authorization_code' => $wechat[$type . '_authorization_code']
        ];
        $res = $this->curl_post_ssl($url, json_encode($data));
        if ($res['authorizer_access_token']) {
            $tokenData = [
                $type . '_authorizer_access_token' => $res['authorizer_access_token'],
                $type . '_authorizer_refresh_token' => $res['authorizer_refresh_token'],
                $type . '_token_expires_time' => time() + 7200
            ];
            //TODO 此处应判断商户是否给足了开发者权限，通过$res['func_info']数组去判断，必要的功能权限不足则应给出相应的错误提示
//            ID为1到26分别代表： 1、消息管理权限 2、用户管理权限 3、帐号服务权限 4、网页服务权限 5、微信小店权限
//            6、微信多客服权限 7、群发与通知权限 8、微信卡券权限 9、微信扫一扫权限 10、微信连WIFI权限 11、素材管理权限
//            12、微信摇周边权限 13、微信门店权限 14、微信支付权限 15、自定义菜单权限 16、获取认证状态及信息
//            17、帐号管理权限（小程序） 18、开发管理与数据分析权限（小程序） 19、客服消息管理权限（小程序）
//            20、微信登录权限（小程序） 21、数据分析权限（小程序） 22、城市服务接口权限 23、广告管理权限 24、开放平台帐号管理权限
//            25、 开放平台帐号管理权限（小程序） 26、微信电子发票权限 请注意： 1）该字段的返回不会考虑公众号是否具备该权限集的权限（因为可能部分具备），请根据公众号的帐号类型和认证情况，来判断公众号的接口权限。
            $res = $wechatSet->_update(['admin_id' => $aid], $tokenData);
            if (!$res) {
                $this->error = '获取商户' . $name . 'authorizer_access_token失败';
                return false;
            }
            $wechatSet->_redisGenerate($aid);
            return $res['authorizer_access_token'];
        }
        return false;
    }

    //获取（刷新）授权公众号或小程序的接口调用凭据（令牌）
//该API用于在授权方令牌（authorizer_access_token）失效时，可用刷新令牌（authorizer_refresh_token）获取新的令牌。
//请注意，此处token是2小时刷新一次，开发者需要自行进行token的缓存，避免token的获取次数达到每日的限定额度。
//type值为wx和xcx,分别对应调用公众号和小程序的授权
    public function getAuthorizationAcessTokenAgain($aid, $type = 'wx')
    {
        $name = $type == 'wx' ? '公众号' : '小程序';
        $wechatSet = new WechatSet();
        $wechat = $wechatSet->_redisGetOneByAid($aid);
        if (!$wechat[$type . '_authorization_code']) {
            $this->error = '该商户' . $name . '暂未授权';
            return false;
        }
        if ($wechat[$type . '_authorizer_access_token'] && (wechat[$type . '_token_expires_time'] - time() < 7200)) {
            return $wechat['authorizer_access_token'];
        }
        $component_access_token = $this->getComponentAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . $component_access_token;
        $data = [
            'component_appid' => $this->appId,
            'authorizer_appid' => $wechat[$type . '_app_id'],
            'authorizer_refresh_token' => $wechat[$type . '_authorizer_refresh_token']
        ];
        $res = $this->curl_post_ssl($url, json_encode($data));
        if ($res['authorizer_access_token']) {
            $tokenData = [
                $type . '_authorizer_access_token' => $res['authorizer_access_token'],
                $type . '_authorizer_refresh_token' => $res['authorizer_refresh_token'],
                $type . '_token_expires_time' => time() + 7200
            ];
            $res = $wechatSet->_update(['admin_id' => $aid], $tokenData);
            if (!$res) {
                $this->error = '更新商户' . $name . 'authorizer_access_token失败';
                return false;
            }
            return $res['authorizer_access_token'];
        }
        return false;
    }

    //获取授权方的帐号基本信息
//该API用于获取授权方的基本信息，包括头像、昵称、帐号类型、认证类型、微信号、原始ID和二维码图片URL。
//需要特别记录授权方的帐号类型，在消息及事件推送时，对于不具备客服接口的公众号，需要在5秒内立即响应；而若有客服接口，
//则可以选择暂时不响应，而选择后续通过客服接口来发送消息触达粉丝。
//type值为wx和xcx,分别对应调用公众号和小程序的授权
    public function getAuthorizerInfo($aid, $type = 'wx')
    {
        $name = $type == 'wx' ? '公众号' : '小程序';
        $wechatSet = new WechatSet();
        $wechat = $wechatSet->_redisGetOneByAid($aid);
        if (!$wechat[$type . '_authorization_code']) {
            $this->error = '该商户' . $name . '暂未授权';
            return false;
        }
        $component_access_token = $this->getComponentAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' . $component_access_token;
        $data = [
            'component_appid' => $this->appId,
            'authorizer_appid' => $wechat[$type . '_app_id'],
        ];
        $res = $this->curl_post_ssl($url, json_encode($data));
        if ($res['authorizer_info']) {
//            dd($res['authorizer_info']);
            if (!$res['verify_type_info']['id'] == -1) {
                $this->error = '该' . $name . '未认证';
                return false;
            }
            return $res['authorizer_info'];
        }
        return false;
    }

    /**
     * 用SHA1算法生成安全签名
     * @param string $token 票据
     * @param string $timestamp 时间戳
     * @param string $nonce 随机字符串
     * @param string $encrypt 密文消息
     */
    public function getSHA1($token, $timestamp, $nonce, $encrypt_msg)
    {
        //排序
        try {
            $array = array($encrypt_msg, $token, $timestamp, $nonce);
            sort($array, SORT_STRING);
            $str = implode($array);
            return array(self::$OK, sha1($str));
        } catch (Exception $e) {
            //print $e . "\n";
            return array(self::$ComputeSignatureError, null);
        }
    }

    /**
     * 提取出xml数据包中的加密消息
     * @param string $xmltext 待提取的xml字符串
     * @return string 提取出的加密消息字符串
     */
    public function extract($xmltext)
    {
        try {
            $xml = new \DOMDocument();
            $xml->loadXML($xmltext);
            $array_e = $xml->getElementsByTagName('Encrypt');
            $array_a = $xml->getElementsByTagName('ToUserName');
            $encrypt = $array_e->item(0)->nodeValue;
            $tousername = $array_a->item(0)->nodeValue;
            return array(0, $encrypt, $tousername);
        } catch (Exception $e) {
            //print $e . "\n";
            return array(self::$ParseXmlError, null, null);
        }
    }

    /**
     * 生成xml消息
     * @param string $encrypt 加密后的消息密文
     * @param string $signature 安全签名
     * @param string $timestamp 时间戳
     * @param string $nonce 随机字符串
     */
    public function generate($encrypt, $signature, $timestamp, $nonce)
    {
        $format = "<xml>
                    <Encrypt><![CDATA[%s]]></Encrypt>
                    <MsgSignature><![CDATA[%s]]></MsgSignature>
                    <TimeStamp>%s</TimeStamp>
                    <Nonce><![CDATA[%s]]></Nonce>
                    </xml>";
        return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
    }

    /**
     * 对需要加密的明文进行填充补位
     * @param $text 需要进行填充补位操作的明文
     * @return 补齐明文字符串
     */
    function encode($text)
    {
        $block_size = self::$block_size;
        $text_length = strlen($text);
        //计算需要填充的位数
        $amount_to_pad = self::$block_size - ($text_length % self::$block_size);
        if ($amount_to_pad == 0) {
            $amount_to_pad = self::block_size;
        }
        //获得补位所用的字符
        $pad_chr = chr($amount_to_pad);
        $tmp = "";
        for ($index = 0; $index < $amount_to_pad; $index++) {
            $tmp .= $pad_chr;
        }
        return $text . $tmp;
    }

    /**
     * 对解密后的明文进行补位删除
     * @param decrypted 解密后的明文
     * @return 删除填充补位后的明文
     */
    function decode($text)
    {

        $pad = ord(substr($text, -1));
        if ($pad < 1 || $pad > 32) {
            $pad = 0;
        }
        return substr($text, 0, (strlen($text) - $pad));
    }

    /**
     * 对明文进行加密
     * @param string $text 需要加密的明文
     * @return string 加密后的密文
     */
    public function encrypt($text, $appid)
    {

        try {
            //获得16位随机字符串，填充到明文之前
            $random = $this->getRandomStr();
            $text = $random . pack("N", strlen($text)) . $text . $appid;
            // 网络字节序
            $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
            $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
            $iv = substr($this->key, 0, 16);
            //使用自定义的填充方式对明文进行补位填充
            $text = $this->encode($text);
            mcrypt_generic_init($module, $this->key, $iv);
            //加密
            $encrypted = mcrypt_generic($module, $text);
            mcrypt_generic_deinit($module);
            mcrypt_module_close($module);

            //print(base64_encode($encrypted));
            //使用BASE64对加密后的字符串进行编码
            return array(self::$OK, base64_encode($encrypted));
        } catch (Exception $e) {
            //print $e;
            return array(self::$EncryptAESError, null);
        }
    }

    /**
     * 对密文进行解密
     * @param string $encrypted 需要解密的密文
     * @return string 解密得到的明文
     */
    public function decrypt($encrypted, $appid)
    {

        try {
            //使用BASE64对需要解密的字符串进行解码
            $ciphertext_dec = base64_decode($encrypted);
            $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
            $iv = substr($this->key, 0, 16);
            mcrypt_generic_init($module, $this->key, $iv);

            //解密
            $decrypted = mdecrypt_generic($module, $ciphertext_dec);
            mcrypt_generic_deinit($module);
            mcrypt_module_close($module);
        } catch (Exception $e) {
            return array(self::$DecryptAESError, null);
        }


        try {
            //去除补位字符
            $result = $this->decode($decrypted);
            //去除16位随机字符串,网络字节序和AppId
            if (strlen($result) < 16)
                return "";
            $content = substr($result, 16, strlen($result));
            $len_list = unpack("N", substr($content, 0, 4));
            $xml_len = $len_list[1];
            $xml_content = substr($content, 4, $xml_len);
            $from_appid = substr($content, $xml_len + 4);
        } catch (Exception $e) {
            //print $e;
            return array(self::$IllegalBuffer, null);
        }
        if ($from_appid != $appid)
            return array(self::$ValidateAppidError, null);
        return array(0, $xml_content);

    }


    /**
     * 随机生成16位字符串
     * @return string 生成的字符串
     */
    function getRandomStr()
    {

        $str = "";
        $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($str_pol) - 1;
        for ($i = 0; $i < 16; $i++) {
            $str .= $str_pol[mt_rand(0, $max)];
        }
        return $str;
    }

    /**
     * 将公众平台回复用户的消息加密打包.
     * <ol>
     *    <li>对要发送的消息进行AES-CBC加密</li>
     *    <li>生成安全签名</li>
     *    <li>将消息密文和安全签名打包成xml格式</li>
     * </ol>
     *
     * @param $replyMsg string 公众平台待回复用户的消息，xml格式的字符串
     * @param $timeStamp string 时间戳，可以自己生成，也可以用URL参数的timestamp
     * @param $nonce string 随机串，可以自己生成，也可以用URL参数的nonce
     * @param &$encryptMsg string 加密后的可以直接回复用户的密文，包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
     *                      当return返回0时有效
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function encryptMsg($replyMsg, $timeStamp, $nonce, &$encryptMsg)
    {
        $this->setKey($this->encodingAesKey);
        //加密
        $array = $this->encrypt($replyMsg, $this->appId);
        $ret = $array[0];
        if ($ret != 0) {
            return $ret;
        }

        if ($timeStamp == null) {
            $timeStamp = time();
        }
        $encrypt = $array[1];

        //生成安全签名
        $array = $this->getSHA1($this->token, $timeStamp, $nonce, $encrypt);
        $ret = $array[0];
        if ($ret != 0) {
            return $ret;
        }
        $signature = $array[1];

        //生成发送的xml
        $encryptMsg = $this->generate($encrypt, $signature, $timeStamp, $nonce);
        return ['code' => self::$OK, 'signature' => $signature];
    }


    /**
     * 检验消息的真实性，并且获取解密后的明文.
     * <ol>
     *    <li>利用收到的密文生成安全签名，进行签名验证</li>
     *    <li>若验证通过，则提取xml中的加密消息</li>
     *    <li>对消息进行解密</li>
     * </ol>
     *
     * @param $msgSignature string 签名串，对应URL参数的msg_signature
     * @param $timestamp string 时间戳 对应URL参数的timestamp
     * @param $nonce string 随机串，对应URL参数的nonce
     * @param $postData string 密文，对应POST请求的数据
     * @param &$msg string 解密后的原文，当return返回0时有效
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptMsg($msgSignature, $timestamp = null, $nonce, $postData, &$msg)
    {
        if (strlen($this->encodingAesKey) != 43) {
            return self::$IllegalAesKey;
        }

        $this->setKey($this->encodingAesKey);
        //提取密文
        $array = $this->extract($postData);
        $ret = $array[0];

        if ($ret != 0) {
            return $ret;
        }

        if ($timestamp == null) {
            $timestamp = time();
        }

        $encrypt = $array[1];
        $touser_name = $array[2];

        //验证安全签名
        $array = $this->getSHA1($this->token, $timestamp, $nonce, $encrypt);
        $ret = $array[0];

        if ($ret != 0) {
            return $ret;
        }

        $signature = $array[1];
        if ($signature != $msgSignature) {
            return self::$ValidateSignatureError;
        }

        $result = $this->decrypt($encrypt, $this->appId);
        if ($result[0] != 0) {
            return $result[0];
        }
        $msg = $result[1];

        return self::$OK;
    }

    public function curl_post_ssl($url, $postdata, $second = 30, $aHeader = [])
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return json_decode($data, true);
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
}